package com.itheima.controller;

import com.itheima.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 服务调用方
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/findGoodsById/{id}")
    public Goods findGoodsById(@PathVariable("id") int id) {
        //System.out.println("访问成功");

        /*
            远程调用Goods服务中的findById接口
            使用RestTemplate
            1.定义bean restTemplate
            2.注入bean
            3.调用方法
        */

        /*
            动态的从Eureka Server中获取provider的ip和端口号
            1.注入DiscoveryClient对象并激活
            2.调用方法
        */
        List<ServiceInstance> instances = discoveryClient.getInstances("EUREKA-PROVIDER");

        if (instances == null || instances.size() == 0) {
            return null;
        }

        ServiceInstance instance = instances.get(0);
        String host = instance.getHost();
        int port = instance.getPort();


        String url = "http://" + host + ":" + port + "/goods/findById/" + id;
        return restTemplate.getForObject(url, Goods.class);
    }


    /**
     *使用 Ribbon 简化restTemplate调用
     * 1.在声明restTemplate的Bean的时候,添加一个注解@LoadBalanced
     * 2.在使用restTemplate发起请求时,需要定义url时,host:port可以替换为服务提供方的应用名
     * @param id
     * @return
     */
    @RequestMapping("/findGoodsById2/{id}")
    public Goods findGoodsById2(@PathVariable("id") int id) {

        String url = "http://EUREKA-PROVIDER/goods/findById/" + id;
        return restTemplate.getForObject(url, Goods.class);
    }
}
